package edu.gdin.ecommerce.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.hibernate.Session;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Component;

import edu.gdin.ecommerce.model.Role;
import edu.gdin.ecommerce.model.User;

@Component("userDAO")
public class UserDAO extends BaseDAO {

	public User getUserByAccount(String account) {
		return (User) this.getHibernateTemplate().get(User.class, account);
	}
	
	
	public Collection<GrantedAuthority> findRoleByAccount(String account) {

		Session s = this.getHibernateTemplate().getSessionFactory().openSession();
		s.beginTransaction();
		User u = (User) s.get(User.class, account);
		if (u == null)
			return null;
		List<Role> roles = null;
		roles = u.getRoles();
		System.out.println(account + "'s roles num:" + roles.size());
		s.getTransaction().commit();
		s.close();

		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			GrantedAuthorityImpl authority = new GrantedAuthorityImpl(role.getName());
			auths.add(authority);
		}
		return auths;

	}
	
}
